#!/usr/bin/env bash

OS_Mac="MacOS"
OS_Linux="Linux"
OS_Windows="Windows"
OS_WinMing="WinMing"
OS_WinCygwin="WinCygwin"

wkpath=$(pwd)
ztcli=zerotier-cli


searchZerotierCliForWindows() {
  # 使用空格分隔的字符串代替数组
  cliPaths="$1/c/ProgramData/ZeroTier/One/zerotier-cli.bat $1/c/Program Files/ZeroTier/One/zerotier-cli.bat $1/c/Program Files (x86)/ZeroTier/One/zerotier-cli.bat $1/d/ProgramData/ZeroTier/One/zerotier-cli.bat $1/d/Program Files/ZeroTier/One/zerotier-cli.bat $1/d/Program Files (x86)/ZeroTier/One/zerotier-cli.bat $1/e/ProgramData/ZeroTier/One/zerotier-cli.bat $1/e/Program Files/ZeroTier/One/zerotier-cli.bat $1/e/Program Files (x86)/ZeroTier/One/zerotier-cli.bat"

  # 使用for循环遍历路径
  for cli in $cliPaths; do
    if [ -f "$cli" ]; then
      echo "$cli"
      return
    fi
  done
}

addCliAliasForShell() {
  shellrc=$1
  ztcli=$2

  if [ ! -f "$shellrc" ]; then
    echo Add alias to $shellrc ignored because file not exists.
    return
  fi

  existed=$(cat $shellrc | grep -c 'export ZEROTIER_CLI') 2>/dev/null
  if [ "$existed" != "0" ]; then
    echo Add alias to $shellrc skipped because alias already exists.
    return
  fi

  echo >> $shellrc
  echo "# ZeroTier One cli path" >> $shellrc
  echo "export ZEROTIER_CLI='$ztcli'" >> $shellrc
  echo "alias zerotier-cli=\"\\\"\$ZEROTIER_CLI\\\"\"" >> $shellrc
  echo "alias zt=\"\\\"\$ZEROTIER_CLI\\\"\"" >> $shellrc
  echo >> $shellrc

  echo Add alias to $shellrc success.
}

makeCliAliasForWindows() {
  cli=$(searchZerotierCliForWindows "$1")

  addCliAliasForShell '~/.bashrc' "$cli"
  addCliAliasForShell '~/.zshrc' "$cli"
}

searchAndFixCliForWindows() {
  if [ -n "$ZEROTIER_CLI" ]; then
    cli="$ZEROTIER_CLI"
    echo "$cli"
    return
  fi

  cli=$(searchZerotierCliForWindows)
  if [ -z "$cli" ]; then
    echo Zerotier cli batch file not found. Please sure you have install Zerotier correctlly.
    exit 9
  fi

  makeCliAliasForWindows "$1"

  echo "$cli"
}

uNames=`uname -s`
osName=${uNames: 0: 4}
if [ "$osName" == "Darw" ] # Darwin
then
	OS="$OS_Mac"
  ZT_PATH="/Library/Application Support/ZeroTier/One"
elif [ "$osName" == "Linu" ] # Linux
then
  OS="$OS_Linux"
  # iStoreOS
  if [ -f '/etc/config/zero/planet' ]
  then
    ZT_PATH="/etc/config/zero"
    ln -s /etc/config/zero /var/lib/zerotier-one
  else
    ZT_PATH="/var/lib/zerotier-one"
  fi
elif [ "$osName" == "MING" ] # MINGW, windows, git-bash
then
  OS="$OS_Windows"
  ZT_PATH="/c/ProgramData/ZeroTier/One"
  ztcli=$(searchAndFixCliForWindows)
elif [ "$osName" == "CYGW" ] # CYGWIN, windows
then
  OS="$OS_Windows"
  ZT_PATH="/cygdrive/c/ProgramData/ZeroTier/One"
  ztcli=$(searchAndFixCliForWindows "/cygdrive")
else
  echo "Unsurported system."
  exit 9
fi


echo
echo "  os: $OS"
echo "path: $ZT_PATH"
echo " cli: $ztcli"
echo

# Parse new planet full path
if [ -n "$1" ]; then
  if [ -e "$1" ]; then
    nppath=`cd $(dirname $1); pwd`
    npfile=`basename $1`
    newplanet="$nppath/$npfile"
  fi
fi

cd "$ZT_PATH"


# 第一次运行, 备份原始设置
ZT_PATH_BACKUP="./planet.ZeroTierOne"
if [ ! -e "./planet.ZeroTierOne/planet" ]; then
  if [ ! -d "$ZT_PATH_BACKUP" ]; then
    mkdir "./planet.ZeroTierOne"
  fi
  cp -f "./planet" "$ZT_PATH_BACKUP/"
  cp -rf "./networks.d" "$ZT_PATH_BACKUP/"
  # cp -rf "./peers.d" "$ZT_PATH_BACKUP/"
fi


planetAlias=
planetAliasError=
if [ -e "$newplanet" ]; then
  planet=${newplanet##*/}
  planetAlias=${planet#*.}

  if [ "$planetAlias" = "$planet" ]; then
    planetAlias=
  fi
  if [ -z "$planetAlias" ]; then
    planetAliasError="Planet filename must be named with alias. Filename formated like: planet.{planet-alias}. Ex: planet.Private"
    planetAlias=
  elif [ -d "./planet.$planetAlias" ]; then
    planetAliasError="Planet [$planetAlias] exists, change another alias or use zerotier-sw with no parameter."
    planetAlias=
  fi

  if [ ! -z "$planetAliasError" ]; then
    echo
    echo $planetAliasError
    echo
    exit 1
  fi
fi


if [ -e "./zerotier-one.planet" ]; then
  currentPlanet=`cat "./zerotier-one.planet"`
else
  currentPlanet="ZeroTierOne"
fi

if [ ! -z "$planetAlias" ]; then
  echo "Import new planet configuration..."
  # copy new planet
  planetPath="./planet.$planetAlias"
  mkdir "$planetPath"
  cp "$newplanet" "$planetPath/planet"
  targetPlanet="$planetAlias"
  echo "Select planet $targetPlanet."
else
  # select planet from list
  echo
  idx=1
  planets=("")
  for file in $(find . -maxdepth 1 -type d | grep "planet.");
  do
    fn=${file##*/}
    falias=${fn#*.}
    planets[idx]=$falias
  if [ "$falias" = "$currentPlanet" ]; then
    curr="*"
  else
    curr=" "
  fi

    echo "$idx. $curr $fn"
    idx=$(($idx + 1))
  done
  echo
  echo "Please select planet(ex: 1 for planet.${planets[1]}): "
  read selectedPlanet
  targetPlanet=${planets[$selectedPlanet]}
  if [ -z "$targetPlanet" ]; then
    echo "Invalid input."
    exit 0
    # targetPlanet="ZeroTierOne"
  fi
  echo "Selected planet: ${planets[$selectedPlanet]}"
fi


  if [ "$targetPlanet" != "$currentPlanet" ]; then
  # Do file swap when target different with current

  # Backup current planet if nesscerry
  if [ ! -e "./planet.$currentPlanet/planet" ]; then
    cp "./planet" "./planet.$currentPlanet/"
  fi

  # Backup networks.d
  if [ -d "./planet.$currentPlanet/networks.d" ]; then
    rm -rf "./planet.$currentPlanet/networks.d"
  fi
  if [ -d "./networks.d" ]; then
    cp -rf "./networks.d" "./planet.$currentPlanet/"
    rm -rf "./networks.d"
  fi

  # # Backup peers.d
  # if [ -d "./planet.$currentPlanet/peers.d" ]; then
  #   rm -rf "./planet.$currentPlanet/peers.d"
  # fi
  # if [ -d "./peers.d" ]; then
  #   cp -rf "./peers.d" "./planet.$currentPlanet/"
  #   rm -rf "./peers.d"
  # fi


  # Copy new planet
  cp -rf "./planet.$targetPlanet/planet" "./"

  # Restore networks.d
  if [ -d "./planet.$targetPlanet/networks.d" ]; then
    cp -rf "./planet.$targetPlanet/networks.d" "./"
  else
    mkdir "./planet.$targetPlanet/networks.d"
  fi

  # # Restore peers.d
  # if [ -d "./planet.$targetPlanet/peers.d" ]; then
  #   cp -rf "./planet.$targetPlanet/peers.d" "./"
  # else
  #   mkdir "./planet.$targetPlanet/peers.d"
  # fi

  # Save new planet
  if [ ! -e "./zerotier-one.planet" ]; then
    touch "./zerotier-one.planet"
  fi
  chmod 666 "./zerotier-one.planet"
  echo "$targetPlanet" > "./zerotier-one.planet"
  chmod 644 "./zerotier-one.planet"
fi

# Restart service
echo "Restart zerotier service..."
if [ "$OS" == "$OS_Mac" ]; then
  cat "./zerotier-one.pid" | xargs kill
  sleep 2
elif [ "$OS" == "$OS_Linux" ]; then
  systemctl restart zerotier-one
  sleep 3
elif [ "$OS" == "$OS_Windows" ]; then
  net stop ZeroTierOneService
  sleep 1
  net start ZeroTierOneService
  sleep 1
fi
echo "Switch planet to $targetPlanet success."
echo

"$ztcli" listpeers
echo
